import React, { PureComponent } from 'react';
import { connect, routerRedux } from 'dva';
import { FirstHeaderC, TableC, PrimaryC, AdvancedSearch, DATA_ENTRY } from '../../comps';
import moment from 'moment';
import { message } from 'antd';

class TaskListC extends PureComponent {
  state = {
    currentPage: 1, //当前页数
    numInPage: 20, //每页条数
    dateObj: undefined, //初始化日期
    TableData: {}, //待办
  };
  componentDidMount() {
    const {
      globalM: {
        dataDictionary: { flow = [] },
      },
      dispatch,
    } = this.props;
    dispatch({
      type: 'agencyTaskM/save',
      payload: {
        selectData: flow,
      },
    });
    if (this.props.type == 0) {
      //待办请求
      // 初始化页面数据
      this.getTableData();
    } else {
      if (sessionStorage.getItem('DoneTaskTime')) return; //首次进入 从props调用 避免重复调用
      if (sessionStorage.getItem('DoneTaskTime1')) {
        //页面刷新 若有值 调用
        this.setState(
          {
            dateObj: JSON.parse(sessionStorage.getItem('DoneTaskTime1')),
          },
          () => {
            let dateObj = this.state.dateObj;
            this.state.RANGEDATE && this.state.RANGEDATE.setDate([moment(dateObj.startTime), moment(dateObj.endTime)]);
            // 初始化页面数据
            this.getTableData();
          },
        );
      }
    }
  }
  UNSAFE_componentWillReceiveProps() {
    if (sessionStorage.getItem('DoneTaskTime') && this.props.type == 1) {
      //从主页反复进入 总是取主页的日期
      this.setState(
        {
          dateObj: JSON.parse(sessionStorage.getItem('DoneTaskTime')),
        },
        () => {
          sessionStorage.setItem('DoneTaskTime1', sessionStorage.getItem('DoneTaskTime'));
          let dateObj = this.state.dateObj;
          if (!dateObj) return;
          this.state.RANGEDATE && this.state.RANGEDATE.setDate([moment(dateObj.startTime), moment(dateObj.endTime)]);
          // 初始化页面数据
          this.getTableData();
          sessionStorage.removeItem('DoneTaskTime'); //清空
        },
      );
    }
  }

  // 调用接口，获取代办列表
  getTableData = () => {
    const { currentPage, numInPage, isReset, dateObj } = this.state;
    const { dispatch } = this.props; //在进入页面时已经请求过 用同一个model
    if (isReset) {
      message.warning('已重置查询条件，请重新查询');
      return;
    }
    //关闭检测刷新标志位
    dispatch({
      type: 'globalM/save',
      payload: { listNeedRefresh: false },
    });
    let search = {};
    let url = this.props.type == 0 ? 'dashboard/getFlowToDoList' : 'dashboard/getFlowDidList'; //已办 待办请求不同接口
    if (this.state.RANGEDATE) {
      let values = this.state.RANGEDATE.props.form.getFieldsValue();
      search.startTime = values.startTime ? moment(values.startTime).format('YYYY-MM-DD') : '';
      search.endTime = values.endTime ? moment(values.endTime).format('YYYY-MM-DD') : '';
    } else {
      //第一次进入
      if (dateObj) {
        search = { ...dateObj };
      }
    }

    dispatch({
      type: url,
      payload: { page: currentPage, pageSize: numInPage, ...search },
      callback: (data) => {
        if (data) {
          this.setState({
            tableData: data,
          });
        } else {
          this.setState({
            tableData: {},
          });
        }
      },
    });
  };

  // 审批/查看
  approvalProcess = (record) => {
    const query =
      this.props.type == 0
        ? {
            taskId: record.taskId, // 流程相关的ID（审批时需要用到）
            businessKey: record.businessKey, // 业务相关的key值 (回填展示详细信息时用到)
            processInstanceId: record.processInstanceId, // 流程相关的ID（获取历史信息用到）
            starter: record.starter, // 任务发起人
            type: record.flowType, // 流程类型
            starterNode: record.starterNode, // 是否是初始节点
          }
        : {
            taskId: record.taskId, // 流程相关的ID（审批时需要用到）
            businessKey: record.businessKey, // 业务相关的key值 (回填展示详细信息时用到)
            processInstanceId: record.processInstanceId, // 流程相关的ID（获取历史信息用到）
            type: record.flowType, // 流程类型
            noOperate: true, //详情无需操作按钮
          };

    // 将数据写入sessionStorage
    sessionStorage.setItem('process', JSON.stringify(query));
    // 跳转到审批页面
    this.props.dispatch(routerRedux.push(`/agencyTask/autoPool`));
  };

  // 改变columns
  changeColumns = (columns) => {
    if (columns && columns.length) {
      // 最后一列添加操作列
      if (columns[columns.length - 1].title != '操作') {
        columns.push({
          title: '操作',
          dataIndex: 'operate',
          key: 'operate',
          type: 'operate',
          operates: [
            {
              title: this.props.type == 0 ? '审批' : '查看',
              onClick: (record) => this.approvalProcess(record),
            },
            // 只在待办消息页面展示
            ...(this.props.type == 0
              ? [
                  {
                    title: '删除',
                    rules: {
                      // 删除逻辑，当前登录用户和流程发起人是同一人且流程为驳回状态时展示删除按钮，后台判断此逻辑返回true/false
                      hide: { items: [{ key: 'isDelete', value: [true], relation: ['!='] }] },
                    },
                    onClick: (record) => this.deleteData(record),
                  },
                ]
              : []),
          ],
        });
      }

      // 转换“流程类型”的值
      columns.map((item) => {
        if (item.key == 'flowType') {
          item.render = (text, record) => {
            const flow = this.props.agencyTaskM.selectData ? this.props.agencyTaskM.selectData.flow : undefined;
            let find = flow && flow.filter((item) => item.code == text);
            if (find && find.length > 0) {
              return find[0].value;
            } else {
              return text;
            }
          };
        }
      });
    }
  };

  // 删除待办任务
  deleteData = (record) => {
    this.props.dispatch({
      type: 'dashboard/deleteData',
      payload: { processInstanceId: record.processInstanceId },
      callback: (type) => {
        if (type) {
          this.getTableData();
        }
      },
    });
  };

  //  表格改变事件
  onChange = ({ current, pageSize, sorter }) => {
    // 刷新页面数据
    this.setState(
      {
        currentPage: current,
        numInPage: pageSize,
      },
      () => {
        this.getTableData();
      },
    );
  };

  render() {
    const { loading, type, nowKey, listNeedRefresh } = this.props;
    const { tableData = {} } = this.state;
    const { dateObj } = this.state;
    const { dataSource, columns, pageInfo } = JSON.stringify(tableData) != '{}' ? tableData : { dataSource: [], columns: [], pageInfo: { currentPage: 0, total: 0, numInPage: 0 } };
    this.changeColumns(columns); // 处理列信息
    let loadingStatus = this.props.type == 0 ? 'dashboard/getFlowToDoList' : 'dashboard/getFlowDidList'; //已办 待办请求不同接口
    if (nowKey && listNeedRefresh && this.props.type == 0 && columns.length) {
      //审批完成请求 nowkey当前tab，listNeedrefresh是否需要刷新列表
      this.setState(
        {
          currentPage: 1,
        },
        () => {
          this.getTableData();
        },
      );
    }
    const searchProps = {
      dataSource: [
        {
          dataIndex: ['startTime', 'endTime'],
          title: '日期区间',
          type: DATA_ENTRY.RANGEDATE,
          initialValue: dateObj ? [moment(dateObj.startTime), moment(dateObj.endTime)] : undefined,
          onRef: (ref) => this.setState({ RANGEDATE: ref }),
        },
      ],
      onQuery: (e) => {
        this.setState(
          {
            //关闭重置标志位
            isReset: false,
            currentPage: 1,
          },
          () => {
            this.getTableData();
          },
        );
      },
      onClear: () => {
        this.setState({
          //开启重置标志位
          isReset: true,
          currentPage: 1,
          numInPage: 20,
        });
      },
    };
    return (
      <div>
        <FirstHeaderC title={type == 0 ? '待办任务' : '已办任务'} />
        {type == 1 && (
          <div style={{ marginBottom: '10px' }}>
            <AdvancedSearch {...searchProps} />
          </div>
        )}
        {type == 0 && (
          <div style={{ width: '100%', textAlign: 'right' }}>
            <PrimaryC
              title='刷新'
              onClick={() => {
                this.setState(
                  {
                    currentPage: 1,
                  },
                  () => {
                    this.getTableData();
                  },
                );
              }}
            />
          </div>
        )}
        <div style={{ marginTop: '10px' }}>
          <TableC
            columns={columns}
            dataSource={dataSource}
            rowKey='taskId'
            loading={loading.effects[loadingStatus] === true}
            onChange={this.onChange}
            current={pageInfo.currentPage}
            total={pageInfo.total}
            pageSize={pageInfo.numInPage}
            selfScrollY={true}
          />
        </div>
      </div>
    );
  }
}
export default connect(({ agencyTaskM, dashboard, loading, globalM }) => ({
  agencyTaskM,
  dashboard,
  loading,
  globalM,
  listNeedRefresh: globalM.listNeedRefresh,
}))(TaskListC);
